package com.zdp.剑指offer;

import com.zdp.util.ListNode;

public class 删除链表的节点 {
    static int Max = 1000;
    public static void main(String[] args) {
        删除链表的节点 demo = new 删除链表的节点();
        for (int i = 10; i <25 ; i++) {
            ListNode p = demo.createList(i);
            demo.outList(p);
            p = demo.DeleteNode(p,i);
            demo.outList(p);
            System.out.println("==============删除值为"+i+"的节点===========");
        }
        //自己测试一个,删除最后一个节点，跟链表只有一个节点的情况
        ListNode p = demo.createList(1);
        demo.outList(p);
        ListNode p1 = p;
        int j=0;
        while(p1!=null){
            if(p1.next==null){
                j = p1.val;
            }
            p1 = p1.next;
        }
        p = demo.DeleteNode(p,j);
        demo.outList(p);
    }
    //删除节点
    ListNode DeleteNode(ListNode head, Integer del){
        ListNode pre = head;
        ListNode p = head;
        if(del==head.val){
            head = head.next;
            return head;
        }
        while(p!=null){
            if(p.val==del){
                pre.next = p.next;
            }
            pre = p;
            p = p.next;
        }
        return head;
    }
    //生成测试数据
    public ListNode createList(int length){
        ListNode head = new ListNode((int)(Math.random()*length+5));
        ListNode result = head;
        for(int i=0;i<length-1;i++){
            ListNode p = new ListNode((int)(Math.random()*length+5));
            head.next = p;
            head = p;
        }
        return result;
    }
    //打印链表
    public void outList(ListNode list){
        while(list!=null){
            if(list.next==null){
                System.out.print(list.val+"\n");
            }else{
                System.out.print(list.val+",");
            }
            list = list.next;
        }
        System.out.println();
    }
}


